// code by onemen
var TMP_Places =
{
   init : function ()
   {
      window.removeEventListener('load', function () { TMP_Places.init(); }, false);

      PlacesController.prototype.openLinksInTabs = this.openLinksInTabs;
      PlacesController.prototype.openSelectedNodeWithEvent = this.openSelectedNodeWithEvent;

      eval("PlacesController.prototype.buildContextMenu ="+PlacesController.prototype.buildContextMenu.toString().replace(
         'return anyVisible;',
         'if (anyVisible) TMP_Places.buildContextMenu(); \ $&'
      ));

      eval("PlacesController.prototype.openSelectedNodeIn ="+PlacesController.prototype.openSelectedNodeIn.toString().replace(
         'openUILinkIn(node.uri, aWhere);',
         'if (aWhere == "current" && !TMP_Places.isBookmarklet(node.uri)) aWhere = TMP_Places.fixWhereToOpen(null, aWhere);\
          $&'
      ));

      // use tab label for bookmark name when user renamed the tab
      if ("PlacesCommandHook" in window) {

         eval("PlacesCommandHook.bookmarkPage ="+PlacesCommandHook.bookmarkPage.toString().replace(
            'title = webNav.document.title;',
            'title = TMP_Places.getTabFixedTitle(aBrowser, url) || webNav.document.title;'
         ));
      
         eval("PlacesCommandHook._getUniqueTabInfo ="+PlacesCommandHook._getUniqueTabInfo.toString().replace(
            'tabList.push(uri);',
            'tabList.push({uri: uri, title: TMP_Places.getTabFixedTitle(browsers[i], uri)});'
         ).replace(
            'seenURIs.uri.spec = true;',
            'seenURIs[uri.spec] = true;'
         ));

      }
   },

   buildContextMenu : function()
   {
      var _open = document.getElementById("placesContext_open");
      var _openInWindow = document.getElementById("placesContext_open:newwindow");
      var _openInTab = document.getElementById("placesContext_open:newtab");
      TMP_updateContextMenu(_open, _openInWindow, _openInTab, prefStringTMBookmark);
   },

   historyMenu : function (aEvent)
   {
      var url = aEvent.target.getAttribute('statustext');
      if (url) {
         var where = this.isBookmarklet(url) ? "current" : 
                      this.fixWhereToOpen(aEvent, whereToOpenLink(aEvent, false, true));
         openUILinkIn(url, where, false, null);
      }
   },

   isBookmarklet : function (url)
   {
      var jsURL = /^ *javascript:/;
      return jsURL.test(url) ? true : false;
   },

   // Check whether the node is a bookmark which should be opened as a web panel
   isOpenInWebPanel : function (node)
   {
      if (PlacesUtils.nodeIsBookmark(node))
         return PlacesUtils.annotations.itemHasAnnotation(node.itemId, LOAD_IN_SIDEBAR_ANNO);

      return false;
   },

   fixWhereToOpen: function (aEvent, aWhere, aPref)
   {
      var w = getTopWin();
      if (!w)
         return aWhere;

      var tabBrowser = w.getBrowser();
      var aTab = tabBrowser.mCurrentTab;

      if (typeof(aPref) == "undefined")
         aPref = prefStringTMBookmark;

      if ((getBoolPref(aPref) || aTab.hasAttribute("locked")))
         if (aEvent && getBoolPref(prefStringTMUseMiddleClick) &&
               (aEvent.button == 1 || aEvent.button == 0 && (aEvent.ctrlKey || aEvent.metaKey)))
            aWhere = "current";
         else if (aWhere == "current"
               && !( tabBrowser.isBlankNotBusyTab(aTab) ))
            aWhere = "tab";

      return aWhere;
   },

   openSelectedNodeWithEvent: function TMP_PC_openSelectedNodeWithEvent(aEvent) {
      var node = this._view.selectedURINode;
      if (node && PlacesUtils.checkURLSecurity(node)) {
         var where = whereToOpenLink(aEvent);
         if (TMP_Places.isOpenInWebPanel(node) && where == "current") {
            var w = getTopWin();
            if (w) {
               w.openWebPanel(node.title, node.uri);
               return;
            }
         }
         where = TMP_Places.isBookmarklet(node.uri) ? "current" : 
                      TMP_Places.fixWhereToOpen(aEvent, where);
         openUILinkIn(node.uri, where, false, null);
      }
   },

   openLinksInTabs: function TMP_PC_openLinksInTabs() {
      var bmGroup = [];
      var node = this._view.selectedNode;
      var selectionIsFolder = this._view.hasSingleSelection && PlacesUtils.nodeIsFolder(node);
      if (selectionIsFolder) {
         var contents = PlacesUtils.getFolderContents(node.itemId, false, false);
         for (var i = 0; i < contents.childCount; ++i) {
            var child = contents.getChild(i);
            if (PlacesUtils.nodeIsURI(child))
               bmGroup.push(child.uri);
         }
      }
      else {
         var nodes = this._view.getSelectionNodes();
         for (i = 0; i < nodes.length; ++i) {
            if (PlacesUtils.nodeIsURI(nodes[i]))
               bmGroup.push(nodes[i].uri);
         }
      }

      // If the bookmark group was completely invalid, just bail.
      if (bmGroup.length != 0) {
         if (!this._confirmOpenTabs(bmGroup.length))
            return;

         var browserWindow = getTopWin();

         if (browserWindow)
            browserWindow.TMP_Bookmark.openGroup(bmGroup, "tab", selectionIsFolder);
         else
            TMP_Places._openBrowserWith(bmGroup.join("|"));
      }

   },

   _openBrowserWith: function TMP_PC__openBrowserWith(url) {
     var win = openDialog("chrome://browser/content/browser.xul", "_blank",
                "chrome,all,dialog=no", url);
     win.openFromPlaces = true;
   },

   _getBookmarkTitle: function TMP_PC__getBookmarkTitle(url)
   {
      var _uri = PlacesUtils._uri(url);
      var _id = PlacesUtils.bookmarks.getBookmarkIdsForURI(_uri, {})[0];
      return _id ? PlacesUtils.bookmarks.getItemTitle(_id): null;
   },

   // start showAddBookmarkUI with user defined title if exist
   getTabFixedTitle: function TMP_PC_getTabFixedTitle(aBrowser, aURI)
   {
      var tabBrowser = getBrowser();
      if (tabBrowser == aBrowser)
         aBrowser = tabBrowser.mCurrentBrowser;

      var aTab = getBrowser().getTabForBrowser(aBrowser);
      if (aTab.getAttribute("label-uri") == aURI.spec)
         return aTab.getAttribute("fixed-label");

      return null;
   }

}
